package com.example.papercut.service.impl;

import com.example.papercut.entity.User;
import com.example.papercut.mapper.UserMapper;
import com.example.papercut.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; // 需要引入 Spring Security 依赖
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final BCryptPasswordEncoder passwordEncoder; // 密码加密器

    @Autowired
    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
        // 实际项目中，通常将 BCryptPasswordEncoder 作为一个 Bean 注入
        this.passwordEncoder = new BCryptPasswordEncoder(); 
    }

    /** 登录逻辑 */
    @Override
    public User login(String identifier, String rawPassword) {
        // 1. 通过用户名或邮箱查找用户
        User user = userMapper.findByUsernameOrEmail(identifier);

        if (user == null) {
            // 用户不存在
            return null; 
        }

        // 2. 比对密码 (rawPassword 是用户输入的明文密码)
        if (passwordEncoder.matches(rawPassword, user.getPassword())) {
            // 登录成功，清除密码敏感信息后返回
            user.setPassword(null); 
            return user;
        } else {
            // 密码错误
            return null;
        }
    }

    /** 注册逻辑 */
    @Override
    @Transactional
    public User register(String username, String email, String rawPassword) {
        // 1. 业务校验：检查用户名和邮箱是否已存在
        if (userMapper.findByUsername(username) != null) {
            throw new IllegalArgumentException("用户名已被占用。");
        }
        if (userMapper.findByEmail(email) != null) {
            throw new IllegalArgumentException("邮箱已被注册。");
        }

        // 2. 创建用户对象并加密密码
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setEmail(email);
        
        // 密码加密存储
        String encodedPassword = passwordEncoder.encode(rawPassword);
        newUser.setPassword(encodedPassword);

        // 3. 插入数据库
        int result = userMapper.insertUser(newUser);
        if (result > 0) {
            newUser.setPassword(null);
            return newUser;
        } else {
            throw new RuntimeException("注册失败，请重试。");
        }
    }
}